package de.wepner.texteditor.model;

import java.io.File;

import de.wepner.texteditor.model.event.Event;


public class EditedFile {
    
    private static final String UNNAMED_FILE_NAME = "<Unnamed>";
    
    private String currentContent = "";
    private File file = null;
    private boolean dirty = false;
    
    private final Event<EditedFile, String> fileNameChangeEvent = new Event<EditedFile, String>(this);
    public final Event<EditedFile, String>.EventAccessor onFileNameChanged = this.fileNameChangeEvent.accessor;
    private final Event<EditedFile, Boolean> dirtyChangeEvent = new Event<EditedFile, Boolean>(this);
    public final Event<EditedFile, Boolean>.EventAccessor onDirtyChanged = this.dirtyChangeEvent.accessor;
    private final Event<EditedFile, String> contentChangeEvent = new Event<EditedFile, String>(this);
    public final Event<EditedFile, String>.EventAccessor onContentChanged = this.contentChangeEvent.accessor;
    
    
    public EditedFile() {
        
    }
    
    public EditedFile(File file, String content) {
        this.setFile(file);
        this.setContent(content);
        this.setDirty(false);
    }
    
    
    public String getName() {
        
        if (this.file != null) {
            return this.file.getName();
        } else {
            return EditedFile.UNNAMED_FILE_NAME;
        }
    }
    
    public File getFile() {
        return this.file;
    }
    
    public void setFile(File file) {
        this.file = file;
        this.fileNameChangeEvent.fireEvent(this.getName());
    }
    
    
    public String getContent() {
        return this.currentContent;
    }
    
    public void setContent(String content) {
        String tmpContent;
        if (content != null) {
            tmpContent = content;
        } else {
            tmpContent = "";
        }
        if (!tmpContent.equals(this.currentContent)) {
            this.currentContent = tmpContent;
            this.setDirty(true);
            this.contentChangeEvent.fireEvent(this.currentContent);
        }
    }
    
    
    public boolean isDirty() {
        return this.dirty;
    }
    
    public void setDirty(final boolean dirty) {
        if (dirty != this.dirty) {
            this.dirty = dirty;
            this.dirtyChangeEvent.fireEvent(Boolean.valueOf(this.dirty));
        }
    }
}
